package vivek.project.pocketmoney.stocks.model.utils
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import mx.collections.ArrayCollection;
	import mx.core.UIComponent;
	import mx.formatters.NumberFormatter;
	import mx.rpc.http.HTTPService;
	import vivek.project.pocketmoney.common.events.ApplicationEvent;
	import vivek.project.pocketmoney.common.utils.StatusBar;
	import vivek.project.pocketmoney.common.utils.StringUtils;
	import vivek.project.pocketmoney.stocks.model.StockDataCache;
	import vivek.project.pocketmoney.stocks.model.StockDataModel;

	public class StockPriceUpdateWorker extends UIComponent
	{

		public function StockPriceUpdateWorker(stockObj:Object)
		{
			getStockPrice(stockObj);
		}
		private var URLData:String=new String();
		private var bsePreviousClose:String=new String();
		private var bseStockPrice:String=new String();
		private var bseTradedTime:String=new String();
		private const bseUrl:String="http://bseindia.com/mktlive/mktwatch.asp";
		private var httpSrv:HTTPService=new HTTPService(bseUrl);
		private var nsePreviousClose:String=new String();
		private var nseStockPrice:String=new String();
		private var nseTradedTime:String=new String();
		private var numberFormatter:NumberFormatter=new NumberFormatter();
		private var paramColl:ArrayCollection;
		private var sdm:StockDataModel=StockDataModel.getInstance();
		private var stockId:int=0;
		private var stockName:String=new String();
		private const stockUrl:String="https://secure.icicidirect.com/trading/equity/trading_stock_quote.asp?Symbol=";
		private var urlReq:URLRequest=new URLRequest(stockUrl);

		private function addStockPriceToDatabase():void
		{
			var obj:Object=new Object();
			obj.stockId=stockId;
			obj.bseStockPrice=bseStockPrice;
			obj.bsePreviousClose=bsePreviousClose;
			obj.nseStockPrice=nseStockPrice;
			obj.nsePreviousClose=nsePreviousClose;
			StockDataCache.stockHistory.addItem(obj);
			sdm.addStockPriceToDatabase(obj);
		}

		private function doBSEEvent(evt:Event):void
		{
			switch (evt.type)
			{
				case Event.COMPLETE: /* If the load was successful, create a URLVariables object from the URLLoader.data property and populate the paramColl ArrayCollection object. */
					var ldr:URLLoader=evt.currentTarget as URLLoader;
					URLData=ldr.data;
					getCurrentBSEPrice();
					break;
				case IOErrorEvent.IO_ERROR:
				{
					dispatchEvent(new ApplicationEvent("StockUpdateEvent", "Stock Price Update Failed", 1));
					break;
				}
			}
		}

		private function doEvent(evt:Event):void
		{
			switch (evt.type)
			{
				case Event.COMPLETE: /* If the load was successful, create a URLVariables object from the URLLoader.data property and populate the paramColl ArrayCollection object. */
					var ldr:URLLoader=evt.currentTarget as URLLoader;
					URLData=ldr.data;
					getCurrentStockPrice();
					addStockPriceToDatabase();
					break;
				case IOErrorEvent.IO_ERROR:
				{
					trace("Error : StockPriceUpdateWorker : " + "");
					break;
				}
			}
		}

		private function getCurrentBSEPrice():void
		{
			var stockPrice:String=StringUtils.stripBetweenNOccurance(URLData, "<font face=arial size=2 color=\"#ic355d\">", 5, "</font>");
			var previousClose:String=StringUtils.stripBetweenNOccurance(URLData, "<font face=arial size=2 color=\"#ic355d\">", 6, "</font>");
			if (stockPrice == "NA")
				stockPrice="0.00";
			if (previousClose == "NA")
				previousClose="0.00";
			stockPrice=StringUtils.trimSpecialChar(stockPrice);
			previousClose=StringUtils.trimSpecialChar(previousClose);
			var bseObject:Object=new Object();
			var percentChange:Number=(parseFloat(stockPrice) - parseFloat(previousClose)) / parseFloat(previousClose) * 100;
			bseObject.stockPrice=stockPrice;
			bseObject.stockName="SENSEX";
			bseObject.previousClose=previousClose;
			numberFormatter.precision=2;
			bseObject.change=(parseFloat(stockPrice) - parseFloat(previousClose));
			bseObject.percentChange=numberFormatter.format(percentChange);
			StockDataCache.stockIndexPrices.source=new Array(); //.removeAll();
			StockDataCache.stockIndexPrices.addItem(bseObject);
			trace(stockName, stockId, stockPrice, previousClose);
		}

		private function getCurrentStockPrice():void
		{
			nseStockPrice=StringUtils.stripBetweenNOccurance(URLData, "<td align=\"right\" class=\"content\">", 1, "</td>");
			nsePreviousClose=StringUtils.stripBetweenNOccurance(URLData, "<td align=\"right\" class=\"content\">", 17, "</td>");
			bseStockPrice=StringUtils.stripBetweenNOccurance(URLData, "<td align=\"right\" class=\"content\">", 2, "</td>");
			bsePreviousClose=StringUtils.stripBetweenNOccurance(URLData, "<td align=\"right\" class=\"content\">", 16, "</td>");
			bseTradedTime=StringUtils.stripBetweenNOccurance(URLData, "<td align=\"center\" class=\"content\">", 3, "</td>");
			nseTradedTime=StringUtils.stripBetweenNOccurance(URLData, "<td align=\"center\" class=\"content\">", 4, "</td>");
			if (nseStockPrice == "NA")
				nseStockPrice="0.00";
			if (nsePreviousClose == "NA")
				nsePreviousClose="0.00";
			if (bseStockPrice == "NA")
				bseStockPrice="0.00";
			if (bsePreviousClose == "NA")
				bsePreviousClose="0.00";
			bseStockPrice=StringUtils.trimSpecialChar(bseStockPrice);
			nseStockPrice=StringUtils.trimSpecialChar(nseStockPrice);
			nsePreviousClose=StringUtils.trimSpecialChar(nsePreviousClose);
			bsePreviousClose=StringUtils.trimSpecialChar(bsePreviousClose);
			trace(stockName, stockId, bseStockPrice, nseStockPrice, nsePreviousClose, bsePreviousClose);
		}

		private function getStockPrice(stockObj:Object):void
		{
			if (stockObj.sc_stocktype == 0)
			{
				var textLoader:URLLoader=new URLLoader();
				this.stockName=stockObj.sc_stockname;
				this.stockId=stockObj.sc_id;
				var textReq:URLRequest=new URLRequest(stockUrl + stockName);
				textLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, doEvent);
				textLoader.addEventListener(IOErrorEvent.IO_ERROR, doEvent);
				textLoader.addEventListener(Event.COMPLETE, doEvent);
				textLoader.load(textReq);
				StatusBar.addMessageToStatusBar("a", 0);
			}
			if (stockObj.sc_stocktype == 1)
			{
				var bseTextLoader:URLLoader=new URLLoader();
				this.stockName=stockObj.sc_stockname;
				this.stockId=stockObj.sc_id;
				var bseTextReq:URLRequest=new URLRequest(bseUrl);
				bseTextLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, doBSEEvent, true);
				bseTextLoader.addEventListener(IOErrorEvent.IO_ERROR, doBSEEvent, true);
				bseTextLoader.addEventListener(Event.COMPLETE, doBSEEvent, true);
				bseTextLoader.load(bseTextReq);
			}
		}
	}
}